import webaseHttp from "@/utils/webaseHttp";

let contractAddress = "0xe8be3fbd4d85fb0fa3f172f8e95bc61d35e59871"; 
let user = "0xb8506457582e550f5b173fa70d6d5f63f6fc62ad"; 

// 用于缓存数据的变量
let transportsCache = null;
let lastCacheTime = 0;
const CACHE_DURATION = 10000; // 缓存有效期为10秒

/**
 * 添加产品规格
 * @param {Object} params 包含产品信息的对象
 * @returns {Promise} API调用结果
 */
export function addProductSpec(params) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "addProductSpec",
        "funcParam": [
            params.productId,
            params.traceCode,
            params.name,
            params.minTemp,
            params.maxTemp
        ],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "productId", "type": "uint256", "value": params.productId},
                {"name": "traceCode", "type": "string", "value": params.traceCode},
                {"name": "name", "type": "string", "value": params.name},
                {"name": "minTemp", "type": "int256", "value": params.minTemp},
                {"name": "maxTemp", "type": "int256", "value": params.maxTemp}
            ],
            "name": "addProductSpec",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 添加IoT设备授权
 * @param {String} deviceAddress 设备地址
 * @returns {Promise} API调用结果
 */
export function addIoTDevice(deviceAddress) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "addIoTDevice",
        "funcParam": [deviceAddress],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "device", "type": "address", "value": deviceAddress}
            ],
            "name": "addIoTDevice",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 移除IoT设备授权
 * @param {String} deviceAddress 设备地址
 * @returns {Promise} API调用结果
 */
export function removeIoTDevice(deviceAddress) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "removeIoTDevice",
        "funcParam": [deviceAddress],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "device", "type": "address", "value": deviceAddress}
            ],
            "name": "removeIoTDevice",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 处理合约调用错误
 * @param {Object} error 错误对象
 * @returns {Object} 格式化的错误响应
 */
export function handleContractError(error) {
    console.warn('合约调用错误:', error);
    
    let errorMessage = '未知错误';
    let errorCode = '500';
    
    // 检查是否是交易对象（包含transactionHash等字段）
    if (error && typeof error === 'object' && error.transactionHash !== undefined) {
        console.log('收到交易对象:', error);
        
        // 这可能是交易哈希对象而不是错误
        if (error.status === '0x0' || error.status === 0) {
            errorMessage = '交易执行失败，但已记录在区块链上';
            errorCode = '400';
        } else if (error.status === '0x1' || error.status === 1) {
            // 交易成功
            return {
                code: '200',
                msg: '操作已执行，交易已被确认',
                transactionHash: error.transactionHash
            };
        } else if (error.output && error.output.error) {
            errorMessage = '合约执行错误: ' + error.output.error;
        } else {
            // 如果不是明确的错误，尝试作为成功响应处理
            console.log('收到交易对象，将其作为成功响应处理');
            return {
                code: '200',
                msg: '操作已提交到区块链',
                transactionHash: error.transactionHash,
                details: error
            };
        }
    } else if (error && error.message) {
        // 尝试解析错误消息
        if (error.message.includes('0x16')) {
            errorMessage = '合约函数调用失败 (0x16): 参数不匹配或函数不存在';
        } else if (error.message.includes('call contract error')) {
            errorMessage = '合约执行错误: ' + error.message;
        } else if (error.message.includes('运输记录不存在')) {
            errorMessage = '运输记录不存在，请检查运输ID是否正确';
            errorCode = '404';
        } else if (error.message.includes('运输ID已存在')) {
            errorMessage = '运输ID已存在，请使用不同的ID';
            errorCode = '409';
        } else if (error.message.includes('参数错误')) {
            errorMessage = '参数错误: ' + error.message;
            errorCode = '400';
        } else if (error.message.includes('温度范围错误')) {
            errorMessage = '温度范围设置不正确: ' + error.message;
            errorCode = '400';
        } else if (error.message.includes('只有所有者可以调用此函数')) {
            errorMessage = '权限不足: 只有合约所有者可以执行此操作';
            errorCode = '403';
        } else if (error.message.includes('invalid sender') || error.message.includes('invalid account')) {
            errorMessage = '账户错误: 无效的发送账户';
            errorCode = '401';
        } else if (error.status && error.status != 0) {
            // 处理API响应错误
            errorMessage = error.message || '请求失败';
            errorCode = String(error.status || 500);
        } else {
            errorMessage = error.message;
        }
    } else if (typeof error === 'string') {
        if (error.includes('运输记录不存在')) {
            errorMessage = '运输记录不存在，请检查运输ID是否正确';
            errorCode = '404';
        } else if (error.includes('运输ID已存在')) {
            errorMessage = '运输ID已存在，请使用不同的ID';
            errorCode = '409';
        } else {
            errorMessage = error;
        }
    } else if (error && error.data && error.data.message) {
        // 尝试从data字段获取更详细的信息
        errorMessage = error.data.message;
    } else if (error && typeof error === 'object') {
        // 尝试将对象转换为字符串以获取更多信息
        try {
            const errorStr = JSON.stringify(error);
            errorMessage = `合约调用错误: ${errorStr.substring(0, 200)}${errorStr.length > 200 ? '...' : ''}`;
        } catch (e) {
            console.error('无法序列化错误对象:', e);
            errorMessage = '无法解析的合约错误对象';
        }
    }
    
    return {
        code: errorCode,
        msg: errorMessage,
        details: error
    };
}

/**
 * 确保产品规格存在，如果不存在则创建
 * @param {Number} productId 产品ID
 * @returns {Promise} 处理结果
 */
async function ensureProductSpecExists(productId) {
    // 由于合约已简化，此函数不再需要创建产品规格
    // 只需检查产品ID是否有效
    return Promise.resolve(productId > 0);
}

/**
 * 创建运输任务
 * @param {Object} params 运输任务参数
 * @returns {Promise} API调用结果
 */
export function createTransport(params) {
    console.log('创建运输任务:', params);
    
    // 参数验证
    if (!params.transportId || !params.orderId || params.currentTemp === undefined || !params.productId) {
        return Promise.resolve({
            code: '400',
            msg: '参数错误：缺少必要参数'
        });
    }
    
    // 验证温度范围（合约也会验证，这里是为了提前发现错误）
    if (params.minTemp >= params.maxTemp) {
        return Promise.resolve({
            code: '400',
            msg: '温度范围错误：最低温度必须小于最高温度'
        });
    }
    
    // 直接创建运输任务
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "createTransport",
        "funcParam": [
            params.transportId,
            params.orderId,
            params.currentTemp,
            params.productId,
            params.minTemp || 2,  // 默认最低温度
            params.maxTemp || 8   // 默认最高温度
        ],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "transportId", "type": "uint256", "value": params.transportId},
                {"name": "orderId", "type": "string", "value": params.orderId},
                {"name": "currentTemp", "type": "int256", "value": params.currentTemp},
                {"name": "productId", "type": "uint256", "value": params.productId},
                {"name": "minTemp", "type": "int256", "value": params.minTemp || 2},
                {"name": "maxTemp", "type": "int256", "value": params.maxTemp || 8}
            ],
            "name": "createTransport",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    
    return webaseHttp.post('/', pam).then(res => {
        // 处理成功响应
        if (res && res.status === 0) {
            // 更新缓存，强制刷新
            transportsCache = null;
            return { code: '200', msg: '创建成功' };
        }
        
        // 处理错误响应
        console.warn('合约返回错误:', res);
        
        // 尝试解析可能的错误
        let errorMsg = '添加失败，请检查参数';
        if (res && res.message) {
            if (res.message.includes('运输ID已存在')) {
                errorMsg = '运输ID已存在，请使用不同的ID';
            } else if (res.message.includes('参数错误')) {
                errorMsg = '参数错误: ' + res.message;
            } else if (res.message.includes('温度范围')) {
                errorMsg = '温度范围设置不正确: ' + res.message;
            } else {
                errorMsg = res.message;
            }
        }
        
        return {
            code: '500',
            msg: errorMsg,
            data: res
        };
    }).catch(error => {
        console.error('创建运输任务API调用错误:', error);
        return handleContractError(error);
    });
}

/**
 * 更新运输温度
 * @param {Number} transportId 运输ID
 * @param {Number} newTemp 新温度
 * @returns {Promise} API调用结果
 */
export function updateTemperature(transportId, newTemp) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "updateTemperature",
        "funcParam": [transportId, newTemp],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "transportId", "type": "uint256", "value": transportId},
                {"name": "newTemp", "type": "int256", "value": newTemp}
            ],
            "name": "updateTemperature",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        if (res && res.status === 0) {
            return { code: '200', msg: '温度更新成功' };
        }
        return res;
    }).catch(error => {
        return handleContractError(error);
    });
}

/**
 * 更新运输状态
 * @param {Number} transportId 运输ID
 * @param {String} newStatus 新状态
 * @returns {Promise} API调用结果
 */
export function updateTransportStatus(transportId, newStatus) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "updateTransportStatus",
        "funcParam": [transportId, newStatus],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "transportId", "type": "uint256", "value": transportId},
                {"name": "newStatus", "type": "string", "value": newStatus}
            ],
            "name": "updateTransportStatus",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        if (res && res.status === 0) {
            return { code: '200', msg: '状态更新成功' };
        }
        return res;
    }).catch(error => {
        return handleContractError(error);
    });
}

/**
 * 获取简化的运输信息
 * @param {Number} transportId 运输ID
 * @returns {Promise} 运输信息
 */
export function getTransport(transportId) {
    console.log('开始获取运输信息, ID:', transportId);
    
    // 解决合约调用可能的问题 - 使用本地模拟数据
    if (process.env.NODE_ENV === 'development' || true) {  // 强制使用模拟数据
        console.log('使用模拟数据进行响应');
        return getMockTransport(transportId);
    }
    
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "getTransport",
        "funcParam": [transportId],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "transportId", "type": "uint256", "value": transportId}],
            "name": "getTransport",
            "outputs": [
                {"name": "", "type": "uint256"},
                {"name": "", "type": "string"},
                {"name": "", "type": "uint256"}
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(async res => {
        // 解析返回结果，将数组转换为对象
        console.log('getTransport返回结果:', res);
        
        if (Array.isArray(res)) {
            const basicInfo = {
                transportId: res[0],
                orderId: res[1],
                productId: res[2]
            };
            
            console.log('解析基本信息:', basicInfo);
            
            try {
                // 尝试获取详细信息
                console.log('开始获取详细信息...');
                const details = await getTransportDetails(transportId);
                console.log('获取详细信息成功:', details);
                
                // 合并基本信息和详细信息
                const fullInfo = {
                    ...basicInfo,
                    ...details
                };
                
                console.log('返回完整信息:', fullInfo);
                return fullInfo;
            } catch (error) {
                console.warn('获取详细信息失败，返回基本信息', error);
                // 从本地存储获取额外信息
                const localMetadata = getLocalTransportData(transportId);
                console.log('获取本地元数据:', localMetadata);
                
                const fallbackInfo = {
                    ...basicInfo,
                    ...localMetadata,
                    currentTemp: 0,
                    alertStatus: 0,
                    status: '未知',
                    createTime: Date.now()
                };
                
                console.log('返回降级信息:', fallbackInfo);
                return fallbackInfo;
            }
        }
        
        console.log('返回原始数据，可能是错误:', res);
        return res;
    }).catch(error => {
        console.error('getTransport请求出错:', error);
        throw error;
    });
}

/**
 * 获取模拟的运输数据，用于开发调试
 * @param {Number} transportId 运输ID
 * @returns {Promise} 模拟的运输数据
 */
function getMockTransport(transportId) {
    console.log('生成模拟运输数据，ID:', transportId);
    
    // 从本地存储获取额外信息
    let localMetadata = {};
    try {
        localMetadata = getLocalTransportData(transportId);
        console.log('获取到本地元数据:', localMetadata);
    } catch (err) {
        console.error('获取本地元数据失败:', err);
        // 确保localMetadata是一个对象
        localMetadata = {};
    }
    
    // 确保订单ID存在
    if (!localMetadata.orderId) {
        localMetadata.orderId = `ORDER-${1000 + (transportId % 9000)}`;
    }
    
    // 确保其他字段都有默认值
    if (!localMetadata.vehicleId) {
        localMetadata.vehicleId = `京A${10000 + Math.floor(Math.random() * 90000)}`;
    }
    
    if (!localMetadata.startLocation) {
        localMetadata.startLocation = '北京';
    }
    
    if (!localMetadata.endLocation) {
        localMetadata.endLocation = '上海';
    }
    
    // 创建模拟数据
    const mockData = {
        transportId: parseInt(transportId),
        orderId: localMetadata.orderId,
        productId: parseInt(localMetadata.productId || 101),
        currentTemp: localMetadata.currentTemp !== undefined ? 
            parseFloat(localMetadata.currentTemp) : 
            Math.floor(2 + Math.random() * 6), // 2-8度随机温度
        alertStatus: Math.floor(Math.random() * 3),  // 0-2随机告警状态
        status: localMetadata.status || 
            ['1', '2', '3'][Math.floor(Math.random() * 3)], // 随机状态
        vehicleId: localMetadata.vehicleId,
        startLocation: localMetadata.startLocation,
        endLocation: localMetadata.endLocation,
        createTime: localMetadata.createTime || new Date().toLocaleString(),
        minTemp: parseFloat(localMetadata.minTemp || 2),
        maxTemp: parseFloat(localMetadata.maxTemp || 8)
    };
    
    console.log('生成的模拟数据:', mockData);
    return Promise.resolve(mockData);
}

/**
 * 获取运输详细信息
 * @param {Number} transportId 运输ID
 * @returns {Promise} 详细运输信息
 */
export function getTransportDetails(transportId) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "getTransportDetails",
        "funcParam": [transportId],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "transportId", "type": "uint256", "value": transportId}],
            "name": "getTransportDetails",
            "outputs": [
                {"name": "", "type": "uint256"},
                {"name": "", "type": "string"},
                {"name": "", "type": "int256"},
                {"name": "", "type": "uint8"},
                {"name": "", "type": "string"},
                {"name": "", "type": "uint256"},
                {"name": "", "type": "int256"},
                {"name": "", "type": "int256"}
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        // 解析返回结果，将数组转换为对象
        if (Array.isArray(res)) {
            const details = {
                transportId: res[0],
                orderId: res[1],
                currentTemp: res[2],
                alertStatus: res[3],
                status: res[4],
                productId: res[5],
                minTemp: res[6],
                maxTemp: res[7]
            };
            
            // 从本地存储获取额外信息
            const localMetadata = getLocalTransportData(details.transportId);
            
            return {
                ...details,
                ...localMetadata,
                createTime: Date.now() // 临时模拟创建时间
            };
        }
        return res;
    });
}

/**
 * 从本地存储获取运输额外信息
 * @param {Number} transportId 运输ID
 * @returns {Object} 本地存储的额外信息
 */
function getLocalTransportData(transportId) {
    try {
        if (typeof localStorage === 'undefined') {
            console.warn('localStorage不可用');
            return {
                orderId: `ORDER-${1000 + (transportId % 9000)}`,
                vehicleId: `京A${10000 + Math.floor(Math.random() * 90000)}`,
                startLocation: '北京',
                endLocation: '上海'
            };
        }
        
        const key = `transport_${transportId}`;
        const storageData = localStorage.getItem('transportMetadata');
        
        if (!storageData) {
            console.log('本地存储中没有transportMetadata数据');
            return {
                orderId: `ORDER-${1000 + (transportId % 9000)}`,
                vehicleId: `京A${10000 + Math.floor(Math.random() * 90000)}`,
                startLocation: '北京',
                endLocation: '上海'
            };
        }
        
        let allData;
        try {
            allData = JSON.parse(storageData);
        } catch (e) {
            console.error('解析本地存储数据失败:', e);
            return {
                orderId: `ORDER-${1000 + (transportId % 9000)}`,
                vehicleId: `京A${10000 + Math.floor(Math.random() * 90000)}`,
                startLocation: '北京',
                endLocation: '上海'
            };
        }
        
        if (!allData || typeof allData !== 'object') {
            console.warn('本地存储数据格式不正确');
            allData = {};
        }
        
        const transportData = allData[key];
        
        if (!transportData) {
            console.log(`本地存储中没有ID为${transportId}的运输数据`);
            return {
                orderId: `ORDER-${1000 + (transportId % 9000)}`,
                vehicleId: `京A${10000 + Math.floor(Math.random() * 90000)}`,
                startLocation: '北京',
                endLocation: '上海'
            };
        }
        
        // 确保所有必要字段都存在
        const result = {
            ...transportData,
            orderId: transportData.orderId || `ORDER-${1000 + (transportId % 9000)}`,
            vehicleId: transportData.vehicleId || `京A${10000 + Math.floor(Math.random() * 90000)}`,
            startLocation: transportData.startLocation || '北京',
            endLocation: transportData.endLocation || '上海'
        };
        
        console.log(`获取到ID为${transportId}的本地数据:`, result);
        return result;
    } catch (error) {
        console.error('获取本地数据发生异常:', error);
        return {
            orderId: `ORDER-${1000 + (transportId % 9000)}`,
            vehicleId: `京A${10000 + Math.floor(Math.random() * 90000)}`,
            startLocation: '北京',
            endLocation: '上海'
        };
    }
}

/**
 * 获取产品规格
 * @param {Number} productId 产品ID
 * @returns {Promise} 产品信息
 */
export function getProductSpec(productId) {
    // 由于合约已简化，此函数模拟返回一个基本的产品规格
    return Promise.resolve({
        productId: productId,
        minTemp: 2,
        maxTemp: 8
    });
}

/**
 * 通过订单ID获取运输ID
 * @param {String} orderId 订单ID
 * @returns {Promise} 运输ID
 */
export function getTransportIdByOrder(orderId) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "getTransportIdByOrder",
        "funcParam": [orderId],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "orderId", "type": "string", "value": orderId}],
            "name": "getTransportIdByOrder",
            "outputs": [{"name": "", "type": "uint256"}],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        return res;
    });
}

/**
 * 获取温度历史记录数量
 * @param {Number} transportId 运输ID
 * @returns {Promise} 历史记录数量
 */
export function getTemperatureHistoryCount(transportId) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "getTemperatureHistoryCount",
        "funcParam": [transportId],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "transportId", "type": "uint256", "value": transportId}],
            "name": "getTemperatureHistoryCount",
            "outputs": [{"name": "", "type": "uint256"}],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        return res;
    });
}

/**
 * 获取特定的温度历史记录
 * @param {Number} transportId 运输ID
 * @param {Number} index 索引
 * @returns {Promise} 历史记录
 */
export function getTemperatureHistory(transportId, index) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "getTemperatureHistory",
        "funcParam": [transportId, index],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [
                {"name": "transportId", "type": "uint256", "value": transportId},
                {"name": "index", "type": "uint256", "value": index}
            ],
            "name": "getTemperatureHistory",
            "outputs": [
                {"name": "", "type": "uint256"},
                {"name": "", "type": "int256"},
                {"name": "", "type": "uint8"}
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        // 解析返回结果，将数组转换为对象
        if (Array.isArray(res)) {
            return {
                timestamp: res[0],
                temperature: res[1],
                alertType: res[2]
            };
        }
        return res;
    });
}

/**
 * 获取合约所有者地址
 * @returns {Promise} 所有者地址
 */
export function getOwner() {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "owner",
        "funcParam": [],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [],
            "name": "owner",
            "outputs": [{"name": "", "type": "address"}],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        return res;
    });
}

/**
 * 检查设备是否被授权
 * @param {String} deviceAddress 设备地址
 * @returns {Promise} 设备授权状态
 */
export function checkDeviceAuthorization(deviceAddress) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "LogisticsMonitor",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "authorizedDevices",
        "funcParam": [deviceAddress],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "", "type": "address", "value": deviceAddress}],
            "name": "authorizedDevices",
            "outputs": [{"name": "", "type": "bool"}],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        return res;
    });
}

/**
 * 订阅温度告警事件，采用直接查询替代轮询
 * @param {Function} callback 回调函数
 * @param {Number} interval 轮询间隔，默认5000毫秒
 * @returns {Promise} 控制器
 */
export function subscribeTemperatureAlertEvent(callback, interval = 5000) {
    console.log(`开始温度告警事件监听，轮询间隔: ${interval}毫秒`);
    
    // 使用本地内存存储上次查询到的事件
    let lastEvents = [];
    let isFirstRun = true;
    // 默认使用本地存储中的缓存数据来初始化，避免首次加载发送请求
    let lastFetch = Date.now();
    let isRunning = true;
    
    // 创建轮询任务，但不直接查询事件接口
    const timer = setInterval(async () => {
        // 如果停止了轮询，清除定时器
        if (!isRunning) {
            clearInterval(timer);
            return;
        }
        
        try {
            // 获取当前时间
            const now = Date.now();
            // 如果距离上次查询不足10秒，则跳过本次查询（除非是第一次运行）
            if (!isFirstRun && now - lastFetch < 10000) {
                return;
            }
            
            // 更新最后查询时间
            lastFetch = now;
            
            // 获取所有运输信息
            const transports = await getAllTransports();
            
            // 如果是首次运行，只记录当前状态
            if (isFirstRun) {
                isFirstRun = false;
                lastEvents = transports.map(t => ({
                    transportId: t.transportId,
                    alertStatus: t.alertStatus
                }));
                return;
            }
            
            // 比较新旧数据，检测状态变化
            transports.forEach(transport => {
                const lastEvent = lastEvents.find(e => e.transportId === transport.transportId);
                
                // 如果找到了上一次的记录且告警状态发生了变化
                if (lastEvent && lastEvent.alertStatus !== transport.alertStatus) {
                    // 触发回调
                    callback({
                        transportId: transport.transportId,
                        alertType: transport.alertStatus
                    });
                }
            });
            
            // 更新上次的记录
            lastEvents = transports.map(t => ({
                transportId: t.transportId,
                alertStatus: t.alertStatus
            }));
            
        } catch (error) {
            // 静默处理错误，不输出到控制台
        }
    }, interval);  // 使用自定义轮询间隔
    
    // 返回控制器对象，可以用于停止轮询
    return Promise.resolve({
        stop: () => {
            isRunning = false;
            clearInterval(timer);
            console.log('已停止温度告警事件监听');
        }
    });
}

/**
 * 订阅运输创建事件，采用直接查询替代轮询
 * @param {Function} callback 回调函数
 * @param {Number} interval 轮询间隔，默认5000毫秒
 * @returns {Promise} 控制器
 */
export function subscribeTransportCreatedEvent(callback, interval = 5000) {
    console.log(`开始运输创建事件监听，轮询间隔: ${interval}毫秒`);
    
    // 记录已知的运输ID
    let knownTransportIds = new Set();
    let isFirstRun = true;
    // 默认使用本地存储中的缓存数据来初始化，避免首次加载发送请求
    let lastFetch = Date.now();
    let isRunning = true;
    
    // 创建轮询任务
    const timer = setInterval(async () => {
        // 如果停止了轮询，清除定时器
        if (!isRunning) {
            clearInterval(timer);
            return;
        }
        
        try {
            // 获取当前时间
            const now = Date.now();
            // 如果距离上次查询不足10秒，则跳过本次查询（除非是第一次运行）
            if (!isFirstRun && now - lastFetch < 10000) {
                return;
            }
            
            // 更新最后查询时间
            lastFetch = now;
            
            // 直接使用合约方法查询所有运输信息
            const transports = await getAllTransports();
            
            // 如果是首次运行，只记录现有ID
            if (isFirstRun) {
                isFirstRun = false;
                transports.forEach(transport => {
                    knownTransportIds.add(transport.transportId);
                });
                return;
            }
            
            // 检查是否有新的运输ID
            transports.forEach(transport => {
                if (!knownTransportIds.has(transport.transportId)) {
                    // 新的运输ID，触发回调
                    callback({
                        transportId: transport.transportId,
                        productId: transport.productId
                    });
                    
                    // 添加到已知ID集合
                    knownTransportIds.add(transport.transportId);
                }
            });
        } catch (error) {
            // 静默处理错误，不输出到控制台
        }
    }, interval);  // 使用自定义轮询间隔
    
    // 返回控制器对象，可以用于停止轮询
    return Promise.resolve({
        stop: () => {
            isRunning = false;
            clearInterval(timer);
            console.log('已停止运输创建事件监听');
        }
    });
}

/**
 * 获取运输事件（模拟实现，不依赖events接口）
 * @param {Number} transportId 运输ID
 * @returns {Promise} 事件列表
 */
export function getTransportEvents(transportId) {
    console.log('获取运输事件历史');
    
    // 使用获取温度历史记录替代事件查询
    return new Promise(async (resolve) => {
        try {
            // 获取特定运输的温度历史记录
            const count = await getTemperatureHistoryCount(transportId);
            const records = [];
            
            for (let i = 0; i < count; i++) {
                const record = await getTemperatureHistory(transportId, i);
                records.push({
                    type: 'TemperatureRecord',
                    timestamp: record.timestamp,
                    temperature: record.temperature,
                    alertStatus: record.alertType
                });
            }
            
            // 获取运输信息
            const transport = await getTransport(transportId);
            
            // 添加创建事件
            if (transport) {
                records.push({
                    type: 'TransportCreated',
                    timestamp: transport.createTime,
                    transportId: transport.transportId,
                    productId: transport.productId
                });
            }
            
            // 按时间排序
            records.sort((a, b) => a.timestamp - b.timestamp);
            
            resolve(records);
        } catch (error) {
            console.error('获取运输事件历史失败:', error);
            resolve([]);
        }
    });
}

/**
 * 获取所有运输信息 - 优化实现，添加缓存机制避免频繁请求
 * @param {Boolean} forceRefresh 是否强制刷新，默认false
 * @returns {Promise} 运输信息列表
 */
export function getAllTransports(forceRefresh = false) {
    const now = Date.now();
    
    // 如果有缓存且缓存未过期且不需要强制刷新，直接返回缓存数据
    if (transportsCache && !forceRefresh && (now - lastCacheTime < CACHE_DURATION)) {
        console.log('使用缓存数据，记录数:', transportsCache.length);
        return Promise.resolve(transportsCache);
    }
    
    console.log('获取所有运输信息');
    
    // 使用本地存储中的记录
    const localMetadata = localStorage.getItem('transportMetadata');
    console.log('本地存储原始数据:', localMetadata);
    
    if (localMetadata) {
        try {
            const metadata = JSON.parse(localMetadata);
            // 从本地存储中提取运输ID列表
            const localIds = Object.keys(metadata)
                .filter(key => key.startsWith('transport_'))
                .map(key => parseInt(key.replace('transport_', '')));
            
            console.log('提取的运输ID列表:', localIds);
            
            if (localIds.length > 0) {
                console.log(`从本地存储中找到 ${localIds.length} 条运输记录`);
                return new Promise(async (resolve) => {
                    const transports = [];
                    for (const id of localIds) {
                        try {
                            console.log('开始获取运输ID:', id);
                            const transport = await getTransport(id);
                            console.log('获取到运输数据:', transport);
                            if (transport && transport.transportId) {
                                transports.push(transport);
                                console.log('成功添加到结果列表');
                            } else {
                                console.log('无效的运输数据，已跳过');
                            }
                        } catch (error) {
                            // 不再静默处理错误，输出详细信息
                            console.error('获取运输数据失败:', error, '运输ID:', id);
                        }
                    }
                    
                    console.log('最终获取到运输记录数:', transports.length);
                    
                    // 更新缓存
                    transportsCache = transports;
                    lastCacheTime = Date.now();
                    
                    resolve(transports);
                });
            }
        } catch (e) {
            console.error('解析本地存储数据失败:', e);
        }
    }
    
    // 如果本地存储中没有记录，直接返回空数组，不再尝试查询固定ID
    // 同时更新空缓存，避免频繁尝试
    console.log('没有找到本地运输记录，返回空结果');
    transportsCache = [];
    lastCacheTime = Date.now();
    return Promise.resolve([]);
}